package org.jeecg.modules.carRegister.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.RestUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.black.entity.Black;
import org.jeecg.modules.black.service.IBlackService;
import org.jeecg.modules.carRegister.entity.CarRegister;
import org.jeecg.modules.carRegister.service.ICarRegisterService;
import org.jeecg.modules.carRegister.util.TemplateMessageUtil;
import org.jeecg.modules.networking.service.INetWorkingService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.userOpenid.entity.UserOpenid;
import org.jeecg.modules.userOpenid.service.IUserOpenidService;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 车辆登记
 * @Author: jeecg-boot
 * @Date: 2024-07-25
 * @Version: V1.0
 */
@Api(tags = "车辆登记")
@RestController
@RequestMapping("/carRegister/carRegister")
@Slf4j
public class CarRegisterController extends JeecgController<CarRegister, ICarRegisterService> {
    @Value(value = "${jeecg.uploadType}")
    private String uploadType;
    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    @Autowired
    private ICarRegisterService carRegisterService;
    @Autowired
    private INetWorkingService netWorkingService;
    @Autowired
    private TemplateMessageUtil templateMessageUtil;
    @Autowired
    private IUserOpenidService userOpenidService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private IBlackService blackService;

    private static final String REGISTER_CALLBACK_URL = "http://39.105.40.67:47555/jeecg-boot/carRegister/carRegister/m/addCarRegister";

    /**
     * 分页列表查询
     *
     * @param carRegister carRegister
     * @param pageNo      pageNo
     * @param pageSize    pageSize
     * @param req         req
     * @return Result
     */
    @ApiOperation(value = "车辆登记-分页列表查询", notes = "车辆登记-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(CarRegister carRegister,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<CarRegister> queryWrapper = QueryGenerator.initQueryWrapper(carRegister, req.getParameterMap());
        Page<CarRegister> page = new Page<CarRegister>(pageNo, pageSize);
        IPage<CarRegister> pageList = carRegisterService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @ApiOperation(value = "车辆登记-对外-分页列表查询", notes = "车辆登记-对外-分页列表查询")
    @GetMapping(value = "/m/list")
    public Result<?> mQueryPageList(CarRegister carRegister,
                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                    HttpServletRequest req) {
        QueryWrapper<CarRegister> queryWrapper = QueryGenerator.initQueryWrapper(carRegister, req.getParameterMap());
        queryWrapper.orderByDesc("create_time");
        Page<CarRegister> page = new Page<CarRegister>(pageNo, pageSize);
        IPage<CarRegister> pageList = carRegisterService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @ApiOperation(value = "车辆登记-对外-分页列表查询", notes = "车辆登记-对外-分页列表查询")
    @GetMapping(value = "/m/deptList")
    public Result<?> mDeptList(CarRegister carRegister,
                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                    HttpServletRequest req) {
        String userId = carRegister.getUserId();
        String deptId = carRegister.getDeptId();
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(deptId)){
            return Result.error("部门id或用户id为空");
        }
        List<String> deptIds = Arrays.asList(deptId.split(","));
        carRegister.setUserId(null).setDeptId(null).setAuditStatus(null).setRegisterStatus(null);
        QueryWrapper<CarRegister> queryWrapper = QueryGenerator.initQueryWrapper(carRegister, req.getParameterMap());
        queryWrapper.eq("register_status", 1);
        queryWrapper.and(w -> w.eq(!StringUtils.isEmpty(userId), "user_id", userId).eq("audit_status", 1))
                .or(w -> w.in(!StringUtils.isEmpty(deptId), "dept_id", deptIds)
                .eq(!StringUtils.isEmpty(deptId), "audit_status", 2));
        queryWrapper.orderByDesc("create_time");
        Page<CarRegister> page = new Page<CarRegister>(pageNo, pageSize);
        IPage<CarRegister> pageList = carRegisterService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @ApiOperation(value = "车辆登记-对外-分页列表查询", notes = "车辆登记-对外-分页列表查询")
    @GetMapping(value = "/m/productList")
    public Result<?> mProductList(CarRegister carRegister,
                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                               HttpServletRequest req) {
        String userId = carRegister.getUserId();
        if (StringUtils.isEmpty(userId)){
            return Result.error("用户id为空");
        }
        carRegister.setUserId(null).setDeptId(null).setAuditStatus(null).setRegisterStatus(null);
        QueryWrapper<CarRegister> queryWrapper = QueryGenerator.initQueryWrapper(carRegister, req.getParameterMap());
        queryWrapper.eq("register_status", 1)
                .and(wq -> wq.and(w -> w.eq(!StringUtils.isEmpty(userId), "user_id", userId)
                                .eq("audit_status", 1)).or().eq("audit_status", 4));
        queryWrapper.orderByDesc("create_time");
        Page<CarRegister> page = new Page<CarRegister>(pageNo, pageSize);
        IPage<CarRegister> pageList = carRegisterService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @ApiOperation(value = "车辆登记-分页列表查询", notes = "车辆登记-分页列表查询")
    @GetMapping(value = "/leadingList")
    public Result<?> leadingList(CarRegister carRegister,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<CarRegister> queryWrapper = QueryGenerator.initQueryWrapper(carRegister, req.getParameterMap());
        queryWrapper.eq("leading_enterprise", 1);
        Page<CarRegister> page = new Page<CarRegister>(pageNo, pageSize);
        IPage<CarRegister> pageList = carRegisterService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @ApiOperation(value = "车辆登记-审批列表", notes = "车辆登记-审批列表")
    @GetMapping(value = "/examineList")
    public Result<?> examineList(CarRegister carRegister,
                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 HttpServletRequest req) {
        QueryWrapper<CarRegister> queryWrapper = QueryGenerator.initQueryWrapper(carRegister, req.getParameterMap());
        queryWrapper.ne("register_status", 1);
        Page<CarRegister> page = new Page<CarRegister>(pageNo, pageSize);
        IPage<CarRegister> pageList = carRegisterService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @ApiOperation(value = "车辆登记-移动端-获取主界面未读消息", notes = "车辆登记-移动端-获取主界面未读消息")
    @GetMapping(value = "/m/getUnread")
    public Result<?> getUnread(@RequestParam(name = "userId") String userId,
                               @RequestParam(name = "deptId") String deptId) {
        List<String> deptIds = Arrays.asList(deptId.split(","));
        LambdaQueryWrapper<CarRegister> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CarRegister::getRegisterStatus, 1);
        wrapper.in(CarRegister::getAuditStatus, 1, 2, 4);
        List<CarRegister> list = carRegisterService.list(wrapper);
        // 使用Stream API进行筛选和计数
        long demandUnitPreliminaryReview = list.stream()
                .filter(car -> car.getAuditStatus() == 1 && userId.equals(car.getUserId()))
                .count();

        long demandUnitConfirmation = list.stream()
                .filter(car -> (car.getAuditStatus() == 2 && deptIds.contains(car.getDeptId())) ||
                        (car.getAuditStatus() == 1 && userId.equals(car.getUserId())))
                .count();

        long productionSupportCenterApproval = list.stream()
                .filter(car -> car.getAuditStatus() == 4 ||
                        (car.getAuditStatus() == 1 && userId.equals(car.getUserId())))
                .count();
        Map<String, Long> map = new HashMap<>();
        map.put("需求单位初审", demandUnitPreliminaryReview); //1 && userid
        map.put("需求单位确认", demandUnitConfirmation); //2 && deptId && role
        map.put("生产保障中心审批", productionSupportCenterApproval); //4 && role


        return Result.OK(map);
    }

    /**
     * 添加
     *
     * @param carRegister carRegister
     * @return Result
     */
    @AutoLog(value = "子系统-审批通过")
    @ApiOperation(value = "子系统-审批通过", notes = "子系统-审批通过")
    @PostMapping(value = "/pass")
    public Result<?> pass(@RequestBody CarRegister carRegister) {
        CarRegister byId = carRegisterService.getById(carRegister.getId());
        if (byId == null) {
            return Result.error("未找到对应数据");
        }
        byId.setEvnType(carRegister.getEvnType());
        byId.setRegisterStatus(1);
        carRegisterService.updateById(byId);
        String json = JSON.toJSONString(carRegister);
        JSONObject jsonObject = JSON.parseObject(json);
        RestUtil.post(REGISTER_CALLBACK_URL, jsonObject);
        UserOpenid byUserId = userOpenidService.getByUserId(byId.getUserId());
        if (byUserId != null){
            templateMessageUtil.sendCarOA(byUserId.getOpenid(), byId.getPlateNo(), byId.getDriverName());
        }
        return Result.OK("审批成功！");
    }

    @AutoLog(value = "子系统-对外-审批通过")
    @ApiOperation(value = "子系统-对外-审批通过", notes = "子系统-对外-审批通过")
    @PostMapping(value = "/m/pass")
    public Result<?> mPass(@RequestParam(name = "id", required = false) String id,
                           @RequestParam(name = "envType", required = false, defaultValue = "") String envType) {
        if (StringUtils.isEmpty(id)) {
            return Result.error("路径参数【id】为空");
        }
        if (StringUtils.isEmpty(envType)) {
            return Result.error("路径参数【envType】为空");
        }
        CarRegister one = carRegisterService.getById(id);
        if (one == null) {
            return Result.error("未找到对应数据");
        }
        one.setRegisterStatus(1);
        one.setEvnType(envType);
        carRegisterService.updateById(one);
        UserOpenid byUserId = userOpenidService.getByUserId(one.getUserId());
        templateMessageUtil.sendCarOA(byUserId.getOpenid(), one.getPlateNo(), one.getDriverName());
        return Result.OK("审批成功！");
    }

    @AutoLog(value = "子系统-对外-允许入厂")
    @ApiOperation(value = "子系统-对外-允许入厂", notes = "子系统-对外-允许入厂")
    @PostMapping(value = "/m/allow")
    public Result<?> mAllow(@RequestParam(name = "id") String id) {
        CarRegister one = carRegisterService.getById(id);
        if (one == null) {
            return Result.error("未找到对应数据");
        }
        one.setApprovalStatus(1);
        carRegisterService.updateById(one);
        return Result.OK("审批成功！");
    }

    @AutoLog(value = "子系统-移动端-审核")
    @ApiOperation(value = "子系统-移动端-审核", notes = "子系统-移动端-审核")
    @PostMapping(value = "/m/audit")
    public Result<?> mAudit(@RequestBody CarRegister carRegister) {
        Integer auditStatus = carRegister.getAuditStatus();
        carRegisterService.updateById(carRegister);
        if (auditStatus == 2) {//初审合格，给部门负责人发待审核消息
            String deptId = carRegister.getDeptId();
            LambdaQueryWrapper<SysUser> wrapper = Wrappers.lambdaQuery();
            wrapper.like(SysUser::getDepartIds, deptId);
            List<SysUser> list = sysUserService.list(wrapper);
            List<String> collect = list.stream().map(SysUser::getId).collect(Collectors.toList());
            List<UserOpenid> byUserIds = userOpenidService.getByUserIds(collect);
            for (UserOpenid userOpenid : byUserIds) {
                templateMessageUtil.sendCarOA(userOpenid.getOpenid(), carRegister.getPlateNo(), carRegister.getDriverName());
            }
        } else if (auditStatus == 3) {//初审驳回，给司机发驳回消息
            sendRejectToDriver(carRegister);
        } else if (auditStatus == 4) {//部门领导通过，给生产保障中心发待审核消息
            LambdaQueryWrapper<SysUserRole> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(SysUserRole::getRoleId, "1978749522551640066");//生产保障中心角色ID
            List<SysUserRole> list = sysUserRoleService.list(wrapper);
            List<String> collect = list.stream().map(SysUserRole::getUserId).collect(Collectors.toList());
            List<UserOpenid> byUserIds = userOpenidService.getByUserIds(collect);
            for (UserOpenid userOpenid : byUserIds) {
                templateMessageUtil.sendCarOA(userOpenid.getOpenid(), carRegister.getPlateNo(), carRegister.getDriverName());
            }
        } else if (auditStatus == 5) {//部门领导驳回，给被访人和司机发驳回消息
            sendRejectToUser(carRegister);
            sendRejectToDriver(carRegister);
        } else if (auditStatus == 6) {//生产保障中心通过，给司机发成功消息
            templateMessageUtil.sendSuccessOA(carRegister.getOpenId(), carRegister.getPlateNo(), carRegister.getDriverName());
        } else if (auditStatus == 7) {//生产保障中心驳回，给被访人和部门领导和司机发驳回消息
            sendRejectToUser(carRegister);
            sendRejectToDriver(carRegister);
            String deptId = carRegister.getDeptId();
            LambdaQueryWrapper<SysUser> wrapper = Wrappers.lambdaQuery();
            wrapper.like(SysUser::getDepartIds, deptId);
            List<SysUser> list = sysUserService.list(wrapper);
            List<String> collect = list.stream().map(SysUser::getId).collect(Collectors.toList());
            List<UserOpenid> byUserIds = userOpenidService.getByUserIds(collect);
            for (UserOpenid userOpenid : byUserIds) {
                templateMessageUtil.sendRejectOA(userOpenid.getOpenid(), carRegister.getPlateNo(), carRegister.getDriverName(), "9");
            }
        }
        return Result.OK("审批成功！");
    }

    /**
     * 给被访人发待审核消息
     * @param carRegister carRegister
     */
    private void sendAuditToUser(CarRegister carRegister) {
        UserOpenid byUserId = userOpenidService.getByUserId(carRegister.getUserId());
        if (byUserId != null) {
            templateMessageUtil.sendCarOA(byUserId.getOpenid(), carRegister.getPlateNo(), carRegister.getDriverName());
        }
    }

    /**
     * 给司机发驳回消息
     * @param carRegister carRegister
     */
    private void sendRejectToDriver(CarRegister carRegister) {
        templateMessageUtil.sendRejectOA(carRegister.getOpenId(), carRegister.getPlateNo(), carRegister.getDriverName(), "8");
    }

    /**
     * 给被访人发驳回消息
     * @param carRegister carRegister
     */
    private void sendRejectToUser(CarRegister carRegister) {
        UserOpenid byUserId = userOpenidService.getByUserId(carRegister.getUserId());
        if (byUserId != null) {
            templateMessageUtil.sendRejectOA(byUserId.getOpenid(), carRegister.getPlateNo(), carRegister.getDriverName(), "9");
        }
    }

    @AutoLog(value = "车辆登记-转为白名单")
    @ApiOperation(value = "车辆登记-转为白名单", notes = "车辆登记-转为白名单")
    @PostMapping(value = "/whiteList")
    public Result<?> whiteList(@RequestBody CarRegister carRegister) {
        carRegister.setWhiteList(1);
        carRegister.setEntryStatus(0);
        carRegisterService.updateById(carRegister);
        return Result.OK("添加成功！");
    }

    @AutoLog(value = "车辆登记-移出白名单")
    @ApiOperation(value = "车辆登记-移出白名单", notes = "车辆登记-移出白名单")
    @PostMapping(value = "/unWhiteList")
    public Result<?> unWhiteList(@RequestBody CarRegister carRegister) {
        carRegister.setWhiteList(0);
        carRegister.setEntryStatus(1);
        carRegisterService.updateById(carRegister);
        return Result.OK("添加成功！");
    }

    @AutoLog(value = "车辆登记-允许入场")
    @ApiOperation(value = "车辆登记-允许入场", notes = "车辆登记-允许入场")
    @PostMapping(value = "/allowPass")
    public Result<?> allowPass(@RequestBody CarRegister carRegister) {
        carRegister.setApprovalStatus(1);
        carRegisterService.updateById(carRegister);
        return Result.OK("审批成功！");
    }

    @AutoLog(value = "车辆登记-拒绝入场")
    @ApiOperation(value = "车辆登记-拒绝入场", notes = "车辆登记-拒绝入场")
    @PostMapping(value = "/refusePass")
    public Result<?> refusePass(@RequestBody CarRegister carRegister) {
        carRegister.setApprovalStatus(2);
        carRegisterService.updateById(carRegister);
        return Result.OK("审批成功！");
    }

    /**
     * 添加
     *
     * @param carRegister carRegister
     * @return Result
     */
    @AutoLog(value = "车辆登记-添加")
    @ApiOperation(value = "车辆登记-添加", notes = "车辆登记-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody CarRegister carRegister) {
        carRegisterService.save(carRegister);
        return Result.OK("添加成功！");
    }

    /**
     * 外部-添加
     *
     * @param carRegister carRegister
     * @return Result
     */
    @AutoLog(value = "车辆登记-外部-添加")
    @ApiOperation(value = "车辆登记-外部-添加", notes = "车辆登记-外部-添加")
    @PostMapping(value = "/m/addCarRegister")
    public Result<?> addCarRegister(@RequestBody CarRegister carRegister) {
        String plateNo = carRegister.getPlateNo();
        String idCard = carRegister.getIdCard();
        CarRegister lastByPlateNo = carRegisterService.getLastUnApprovalByPlateNo(plateNo);
        List<Black> byPlateAndIdCard = blackService.getByPlateAndIdCard(plateNo, idCard);
        if (byPlateAndIdCard != null && !byPlateAndIdCard.isEmpty()){
            carRegister.setAuditStatus(8);
        } else {
            carRegister.setAuditStatus(1);
        }
        if (lastByPlateNo == null) {//如果没有未入场且未审批的登记信息，则添加
            carRegisterService.save(carRegister);
        } else {//如果有未入场且未审批的登记信息，则更新
            carRegisterService.removeById(lastByPlateNo.getId());
            carRegisterService.save(carRegister);
        }
        new Thread(() -> {
            try {
                JSONObject jsonObject = netWorkingService.putRegisterVehicleInfo(carRegister);
                log.info("车辆备案结果: {}", jsonObject);
                if (carRegister.getRegisterStatus() == 1){
                    sendAuditToUser(carRegister);
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }).start();
        return carRegister.getAuditStatus() == 8 ? Result.error("黑名单车辆或人员") : Result.OK("添加成功！") ;
    }

    /**
     * 编辑
     *
     * @param carRegister carRegister
     * @return Result
     */
    @AutoLog(value = "车辆登记-编辑")
    @ApiOperation(value = "车辆登记-编辑", notes = "车辆登记-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody CarRegister carRegister) {
        carRegisterService.updateById(carRegister);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id id
     * @return Result
     */
    @AutoLog(value = "车辆登记-通过id删除")
    @ApiOperation(value = "车辆登记-通过id删除", notes = "车辆登记-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        carRegisterService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids ids
     * @return Result
     */
    @AutoLog(value = "车辆登记-批量删除")
    @ApiOperation(value = "车辆登记-批量删除", notes = "车辆登记-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.carRegisterService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id id
     * @return Result
     */
    @AutoLog(value = "车辆登记-通过id查询")
    @ApiOperation(value = "车辆登记-通过id查询", notes = "车辆登记-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        CarRegister carRegister = carRegisterService.getById(id);
        if (carRegister == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(carRegister);
    }

    @AutoLog(value = "车辆登记-通过id查询")
    @ApiOperation(value = "车辆登记-通过id查询", notes = "车辆登记-通过id查询")
    @GetMapping(value = "/m/queryById")
    public Result<?> mQueryById(@RequestParam(name = "id", required = true) String id) {
        CarRegister carRegister = carRegisterService.getById(id);
        if (carRegister == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(carRegister);
    }

    /**
     * 导出excel
     *
     * @param request     request
     * @param carRegister carRegister
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CarRegister carRegister) {
        return super.exportXls(request, carRegister, CarRegister.class, "车辆登记");
    }

    @RequestMapping(value = "/leadingExportXls")
    public ModelAndView leadingExportXls(HttpServletRequest request, CarRegister carRegister) {
        // Step.1 组装查询条件
        QueryWrapper<CarRegister> queryWrapper = QueryGenerator.initQueryWrapper(carRegister, request.getParameterMap());
        queryWrapper.eq("leading_enterprise", 1);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<CarRegister> pageList = carRegisterService.list(queryWrapper);
        List<CarRegister> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(getId(item))).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "车辆登记"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, CarRegister.class);
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams=new ExportParams("车辆登记报表", "导出人:" + sysUser.getRealname(), "车辆登记");
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS,exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request  request
     * @param response response
     * @return Result
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CarRegister.class);
    }

    private String getId(CarRegister item) {
        try {
            return PropertyUtils.getProperty(item, "id").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 文件上传统一方法
     *
     * @param request 请求
     * @return Result
     */
    @PostMapping(value = "/m/upload")
    public Result<?> upload(HttpServletRequest request) {
        Result<?> result = new Result<>();
        String savePath = "";
        String bizPath = DateUtil.formatDate(new Date());
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
//        savePath = this.uploadLocal(file, bizPath);
        savePath = CommonUtils.upload(file, bizPath, uploadType);
        if (oConvertUtils.isNotEmpty(savePath)) {
            result.setMessage(savePath);
            result.setSuccess(true);
        } else {
            result.setMessage("上传失败！");
            result.setSuccess(false);
        }
        return result;
    }

    public MultipartFile saveFileWithoutWaterMark(MultipartFile file) {
        try {
            if ((1024 * 1024 * 0.1) <= file.getSize()) {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                //小于 1M 的
                if ((1024 * 1024 * 0.1) <= file.getSize() && file.getSize() <= (1024 * 1024)) {
                    Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.9f).toOutputStream(outputStream);
                }
                // 1 - 2M 的
                else if ((1024 * 1024) < file.getSize() && file.getSize() <= (1024 * 1024 * 2)) {
                    Thumbnails.of(file.getInputStream()).scale(0.8f).outputQuality(0.6f).toOutputStream(outputStream);
                }// 2M 以上的
                else if ((1024 * 1024 * 2) < file.getSize()) {
                    Thumbnails.of(file.getInputStream()).scale(0.5f).outputQuality(0.3f).toOutputStream(outputStream);
                }

                byte[] bytes = outputStream.toByteArray();
                InputStream inputStream = new ByteArrayInputStream(bytes);
                //Boolean b=ImageIO.write(ImageIO.read(inputStream),"jpg",new File("D:/111.jpg"));
                // 转换城新的 MultipartFile 对象
                MultipartFile fileInfos = new MockMultipartFile(Objects.requireNonNull(file.getOriginalFilename()), file.getOriginalFilename(), file.getContentType(), inputStream);
                log.info("源文件大小:{}压缩后的大小:{}", file.getSize(), fileInfos.getSize());
                return fileInfos;
            }
            return file;

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    @ApiOperation(value = "车辆登记-分类统计", notes = "车辆登记-分类统计")
    @GetMapping(value = "/queryByCount")
    public Result<?> queryByCount() {
        //EnterpriseBasicInformation enterprise = enterpriseBasicInformationService.list().get(0);
        QueryWrapper<CarRegister> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("max(create_time) as create_time");
        Date max = carRegisterService.getOne(queryWrapper).getCreateTime();
        queryWrapper.clear();
        queryWrapper.select("min(create_time) as create_time");
        Date min = carRegisterService.getOne(queryWrapper).getCreateTime();
        long l = (max.getTime() - min.getTime()) / (3600 * 24 * 1000) + 1;
        queryWrapper.clear();
        queryWrapper.select("count(1) as count");
        Map<String, Object> map = carRegisterService.getMap(queryWrapper);
        long total = Long.parseLong(map.get("count").toString());
        long average = total / l;
        // 设置返回值
        List<Map<String, String>> list = carRegisterService.getCount();
        List<Map<String, String>> updatedList = new ArrayList<>();
        for (Map<String, String> mapString : list) {
            Map<String, String> updatedMap = new HashMap<>();
            String name = mapString.get("name");
            switch (name) {
                case "0":
                    updatedMap.put("name", "国零");
                    updatedMap.put("value", mapString.get("value"));
                    break;
                case "1":
                    updatedMap.put("name", "国一");
                    updatedMap.put("value", mapString.get("value"));
                    break;
                case "2":
                    updatedMap.put("name", "国二");
                    updatedMap.put("value", mapString.get("value"));
                    break;
                case "3":
                    updatedMap.put("name", "国三");
                    updatedMap.put("value", mapString.get("value"));
                    break;
                case "4":
                    updatedMap.put("name", "国四");
                    updatedMap.put("value", mapString.get("value"));
                    break;
                case "5":
                    updatedMap.put("name", "国五");
                    updatedMap.put("value", mapString.get("value"));
                    break;
                case "6":
                    updatedMap.put("name", "国六");
                    updatedMap.put("value", mapString.get("value"));
                    break;
                case "D":
                    updatedMap.put("name", "新能源");
                    updatedMap.put("value", mapString.get("value"));
                    break;
                default:
                    updatedMap.put("name", "排放标准未知");
                    updatedMap.put("value", mapString.get("value"));
            }
            updatedList.add(updatedMap);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", updatedList);
        jsonObject.put("total", total);
        jsonObject.put("average", average);
        return Result.OK(jsonObject);
    }

}
